import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:gksz/nav/nav.dart';
import 'package:shared_preferences/shared_preferences.dart';

Dio dio = new Dio();

class Loginpage extends StatefulWidget {
  Loginpage({Key key}) : super(key: key);

  @override
  _LoginpageState createState() => _LoginpageState();
}


class _LoginpageState extends State<Loginpage> {
  final _formKey = GlobalKey<FormState>();
  String _username, _password;
  bool _isObscure = true;
  Color _eyeColor;
  


  get _loginMethod => null;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Form(
            key: _formKey,
            child: ListView(
              padding: EdgeInsets.symmetric(horizontal: 22.0),
              children: <Widget>[
                SizedBox(
                  height: kToolbarHeight,
                ),
                buildTitle(),
                // buildTitleLine(),
                SizedBox(height: 70.0),
                buildUsernameTextField(),
                SizedBox(height: 10.0),
                buildPasswordTextField(context),
                SizedBox(height: 60.0),
                buildLoginButton(context),
                SizedBox(height: 100.0),
                buildTitle2(),
              ],
            )));
  }

    // var _point;
    // var number;
    // var username;

  Align buildLoginButton(BuildContext context) {
    return Align(
      child: SizedBox(
        height: 45.0,
        width: MediaQuery.of(context).size.width*0.6,
        child: RaisedButton(
          child: Text(
            '登录',
            style: Theme.of(context).primaryTextTheme.headline,
          ),

          color: Color.fromRGBO(196, 8, 8, 1),
          onPressed: () async{
            Response response;
            Dio dio = new Dio();
            print('username:$_username , password:$_password');
            // print(this._point['mission']['study']);
            if (_formKey.currentState.validate()) {
              ///只有输入的内容符合要求通过才会到达此处
              _formKey.currentState.save();
              //TODO 执行登录方法
            response = await dio.post("http://xssw.gdit.edu.cn/sizheng/api/v1/login",
              data:{"username":"$_username","password":"$_password"});

              // if (this._point['number'].length == 10) {
              //     if (this._point['mission']['study'] == 'false') {
              //           var newpoint = this._point['point'] + 1;
              //           var pp = await dio.patch(
              //             'http://xssw.gdit.edu.cn/sizheng/api/v1/student/${username}',
              //             data: {'point': newpoint});
              //           var zhuangtai = await dio.patch(
              //             'http://xssw.gdit.edu.cn/sizheng/api/v1/student/${username}',
              //           data: {
              //               "mission": {
              //                  "study": "true",
              //                }
              //           });
              //   Navigator.of(context).pushAndRemoveUntil(
              //   new MaterialPageRoute(builder: (context) => Nav()
              //   ),
              //    (route) => route == null
              //    );
              //  } else {
              //   Navigator.of(context).pushAndRemoveUntil(
              //   new MaterialPageRoute(builder: (context) => Nav()
              //   ),
              //    (route) => route == null
              //    );
              //  }} else {
              //    if (this._point['mission']['study'] == 'false') {
              //        var newpoint = this._point['point'] + 1;
              //        var pp = await dio.patch(
              //           'http://xssw.gdit.edu.cn/sizheng/api/v1/teacher/${username}',
              //           data: {'point': newpoint});
              //        var zhuangtai = await dio.patch(
              //           'http://xssw.gdit.edu.cn/sizheng/api/v1/teacher/${username}',
              //           data: {
              //             "mission": {
              //                "study": "true",
              //             }});
              //   Navigator.of(context).pushAndRemoveUntil(
              //   new MaterialPageRoute(builder: (context) => Nav()
              //   ),
              //    (route) => route == null
              //    );
              // } else {
              //   Navigator.of(context).pushAndRemoveUntil(
              //   new MaterialPageRoute(builder: (context) => Nav()
              //   ),
              //    (route) => route == null
              //    );
              // }}
              
              if(response.data != null){
                print('${response.data['user']}');
                SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
                sharedPreferences.setString('username','${response.data['user']['name']}');
                sharedPreferences.setString('user_id','${response.data['user']['_id']}');
                sharedPreferences.setString('number','${response.data['user']['number']}');
                sharedPreferences.setString('sumjifen','${response.data['user']['point']}');
                // print(sharedPreferences.getString('username'));
              Navigator.of(context).pushAndRemoveUntil(
                new MaterialPageRoute(builder: (context) => Nav()
                ),
                 (route) => route == null
                 );
              //跳转至指定页面
              }else{
                print('err');
                showDialog<Null>(
            context: context,
            barrierDismissible: false,
            builder: (BuildContext context) {
                return new AlertDialog(
                    title: new Text('温馨提示'),
                    content: new SingleChildScrollView(
                        child: new ListBody(
                            children: <Widget>[
                                new Text('您输入的账号信息有误'),
                                new Text('请输入正确的账号信息'),
                            ],
                        ),
                    ),
                    actions: <Widget>[
                        new FlatButton(
                            child: new Text('确定'),
                            onPressed: () {
                                Navigator.of(context).pop();
                            },
                        ),
                    ],
                );
            },
        ).then((val) {
            print(val);
        });
              }
            }
          },
        ),
      ),
    );
  }

  TextFormField buildPasswordTextField(BuildContext context) {
    return TextFormField(
      onSaved: (String value) => _password = value,
      obscureText: _isObscure,
      // validator: (String value) {
      //   if (value.isEmpty) {
      //     return '请输入密码';
      //   }
      // },
      decoration: InputDecoration(
        contentPadding: EdgeInsets.all(10.0),
        border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(15.0),
//            borderSide: BorderSide(color: Colors.red, width: 3.0, style: BorderStyle.solid)//没什么卵效果
          ),
        prefixIcon: Icon(Icons.near_me),
          labelText: '账号密码',
          suffixIcon: IconButton(
              icon: Icon(
                Icons.remove_red_eye,
                color: _eyeColor,
              ),
              onPressed: () {
                setState(() {
                  _isObscure = !_isObscure;
                  _eyeColor = _isObscure
                      ? Colors.grey
                      : Theme.of(context).iconTheme.color;
                });
              })),
    );
  }

  TextFormField buildUsernameTextField() {
    return TextFormField(
      decoration: InputDecoration(
        contentPadding: EdgeInsets.all(10.0),
        border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(15.0),
//            borderSide: BorderSide(color: Colors.red, width: 3.0, style: BorderStyle.solid)//没什么卵效果
          ),
        prefixIcon: Icon(Icons.person),
        labelText: '学号/工号',
      ),
      // validator: (String value) {
      //   var usernameReg = RegExp(
      //       r"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?");
      //   if (!usernameReg.hasMatch(value)) {
      //     return '请输入正确的学号/工号';
      //   }
      // },
      onSaved: (String value) => _username = value,
    );
  }

  // Padding buildTitleLine() {
  //   return Padding(
  //     padding: EdgeInsets.only(left: 12.0, top: 4.0),
  //     child: Align(
  //       alignment: Alignment.bottomLeft,
  //       child: Container(
  //         color: Colors.red,
  //         width: 60.0, 
  //         height: 2.0,
  //       ),
  //     ),
  //   );
  // }

  Padding buildTitle() {
    return Padding(
      padding: EdgeInsets.all(1.0),
      child: Image.asset('images/gksz_logo.png'),
      // Text(
      //   '广科思政',
      //   style: TextStyle(fontSize: 42.0,color: Colors.red,),
      // ),
      
    );
  }

  Padding buildTitle2(){
    return Padding(
      padding: EdgeInsets.all(1.0),
      child: Image.asset('images/gk_logo.jpg'),
    );
  }
}